#!/usr/bin/python

ACCOUNT_FILE = 'account.txt'
PROFILE_INTERVAL = 60

import dictbot
import profiler


def read_AccountInfo(accountFile):
	"Read configuration settings for all accounts"
	accInfo = {}
	for line in open(accountFile).readlines():
		line = line.strip()
		if len(line) > 0 and not line.startswith('#'):	# Not a blank line or a comment
			key, value = line.split(':')
			key = key.strip().lower()
			value = value.strip()
			if accInfo.has_key(key):
				accInfo[key].append(value);
			else:
				accInfo[key] = [value]
	return len(accInfo['username']), accInfo


if __name__ == '__main__':
	localBots = []
	numAccs, accInfo = read_AccountInfo(ACCOUNT_FILE)
	dictbot.DictBot.admins = accInfo['admin']

	for accNum in range(0, numAccs):
		# Treat all accounts as siblings even if it may not be running locally
		domain = accInfo['domain'][accNum]
		username = accInfo['username'][accNum]
		dictbot.DictBot.siblings.append(username + '@' + domain)

		# Load dictionary bots if they are enabled
		if accInfo['enable'][accNum] == '1':
			password = accInfo['password'][accNum]
			url = accInfo['url'][accNum]
			port = int(accInfo['port'][accNum])
			bot = dictbot.DictBot(domain, username, password, url, port)
			
			# Refresh roster for each bot
			for acc in range(0, numAccs):
				domain = accInfo['domain'][acc]
				username = accInfo['username'][acc]
				password = accInfo['password'][acc]
				url = accInfo['url'][acc]
				port = int(accInfo['port'][acc])
				bot.refresh_Roster(domain, username, password, url, port)

			localBots.append(bot)
			bot.start()

	profiler = profiler.Profiler(localBots, PROFILE_INTERVAL)
	profiler.start()
	for bot in localBots:	# Wait until all the bots have terminated
		bot.join()
	profiler.exist = False
	profiler.join()
